#define _CRT_SECURE_NO_WARNINGS 1
#include "Heap.h"

void HPInit(HP* php)
{
	assert(php);
	php->arr = NULL;
	php->capacity = php->size = 0;
}

void HPDestroy(HP* php)
{
	assert(php);
	if (php->arr)
	{
		free(php->arr);
	}
	php->arr = NULL;
	php->capacity = php->size = 0;
}

void Swab(HPDataType* x, HPDataType* y)
{
	HPDataType tmp = *x;
	*x = *y;
	*y = tmp;
}

void AdjustUp(HPDataType* arr, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (arr[child]<arr[parent])
		{
			Swab(&arr[child], &arr[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HPPush(HP* php, HPDataType x)
{
	assert(php);
	if (php->capacity==php->size)
	{
		int newcapcity = php->capacity == 0 ? 4 : 2 * php->capacity;
		HPDataType* new = (HPDataType*)realloc(php->arr, newcapcity * sizeof(HPDataType));
		if (new==NULL)
		{
			perror("realloc!");
			exit(1);
		}
		php->arr = new;
		php->capacity = newcapcity;
	}
	php->arr[php->size] = x;
	AdjustUp(php->arr, php->size);
	++php->size;
}

void AdjustDown(HPDataType* arr,int parent,int n)
{
	int child = parent * 2 + 1;
	while (child<n)
	{
		if (child + 1 < n && arr[child] > arr[child + 1])
		{
			child++;
		}
		if (arr[child]<arr[parent])
		{
			Swab(&arr[child], &arr[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void HPPop(HP* php)
{
	assert(php&&php->size);
	Swab(&php->arr[0], &php->arr[php->size - 1]);
	--php->size;
	AdjustDown(php->arr, 0, php->size);
}


HPDataType HPTop(HP* php)
{
	assert(php && php->size);
	return php->arr[0];
}

bool HPEmpty(HP* php)
{
	assert(php );
	return php->size == 0;
}
